package org.seedframework.sharding.resource;


import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.tomlj.Toml;
import org.tomlj.TomlParseResult;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;


/**
 * Strategy to load TOML files into a {@link PropertySource}.
 */
public class TomlPropertySourceLoader implements PropertySourceLoader {

    /**
     * Returns the file extensions that the loader supports (excluding the '.').
     * @return the file extensions
     */
    @Override
    public String[] getFileExtensions() {
        return new String[] { "toml" };
    }

    /**
     * Load the resource into one or more property sources. Implementations may either
     * return a list containing a single source, or in the case of a multi-document format
     * such as yaml a source for each document in the resource.
     * @param name the root name of the property source. If multiple documents are loaded
     * an additional suffix should be added to the name for each source loaded.
     * @param resource the resource to load
     * @return a list property sources
     * @throws IOException if the source cannot be loaded
     */
    public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
        try (InputStream in = resource.getInputStream()) {
            TomlParseResult source = Toml.parse(in);
            if (source.isEmpty()) {
                return emptyList();
            }

            return singletonList(new MapPropertySource(name, source.toMap()));
        }
    }

}
